// API 入口文件
import axios from 'axios';
import { defaultApiConfig } from '@config/api';
import store from '@store/index';
import { setTokens, clearTokens } from '@store/token';
import { loginSuccess, logout } from '@store/auth';
import {message} from "antd";

// 登录接口响应数据类型
interface LoginResponse {
  message: string;
  data: {
    access_token: string;
    refresh_token: string;
  };
  code: number;
  success: boolean;
}

// 创建 axios 实例
const apiClient = axios.create({
  baseURL: defaultApiConfig.baseUrl,
  timeout: defaultApiConfig.timeout,
});

// 判断是否为白名单路径
const isWhitelisted = (url: string): boolean => {
  return defaultApiConfig.whiteList?.some((path) => url.includes(path)) || false;
};

// 跳转到登录页面
const redirectToLogin = () => {
  // 清除 token
  store.dispatch(clearTokens());
  // 更新认证状态
  store.dispatch(logout());
};

// 刷新 token
const refreshAccessToken = async (): Promise<string | null> => {
  try {
    const state = store.getState();
    const refreshToken = state.token.refreshToken;
    
    if (!refreshToken) {
      return null;
    }
    
    const response = await apiClient.post<LoginResponse>('/auth/refresh', { refresh_token: refreshToken });
    const { data, success } = response.data;
    
    if (success && data && data.access_token) {
      store.dispatch(setTokens({
        accessToken: data.access_token,
        refreshToken: data.refresh_token
      }));
      store.dispatch(loginSuccess());
      return data.access_token;
    }
    
    return null;
  } catch (error) {
    console.error('Failed to refresh token:', error);
    return null;
  }
};

// 请求拦截器
apiClient.interceptors.request.use(
  (config) => {
    // 检查是否为白名单路径
    if (!isWhitelisted(config.url || '')) {
      // 获取 token
      const state = store.getState();
      const token = state.token.accessToken;
      
      // 如果没有 token，跳转到登录页面
      if (!token) {
        redirectToLogin();
        return Promise.reject(new Error('No token available'));
      }
      
      // 添加 Authorization 头
      config.headers.Authorization = `Bearer ${token}`;
    }
    
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
apiClient.interceptors.response.use(
  (response) => {
    return response;
  },
  async (error) => {
    const originalRequest = error.config;
    
    // 如果是 401 错误且不是刷新 token 的请求，并且不是登录或刷新令牌接口
    if (error.response?.status === 401 && !originalRequest._retry && 
        !originalRequest.url?.includes('/auth/login') && 
        !originalRequest.url?.includes('/auth/refresh')) {
      originalRequest._retry = true; // 标记已重试
      
      // 尝试刷新 token
      const newToken = await refreshAccessToken();
      
      if (newToken) {
        // 更新 Authorization 头
        originalRequest.headers.Authorization = `Bearer ${newToken}`;
        // 重新发送请求
        return apiClient(originalRequest);
      } else {
        // 刷新失败，跳转到登录页面
          message.error('登录失效， 请重新登录')
        redirectToLogin();
      }
    }
    
    return Promise.reject(error);
  }
);

// 直接暴露常用的HTTP方法
export const get = apiClient.get;
export const post = apiClient.post;

export default apiClient;